package com.ermax.aircond.util.service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.springframework.stereotype.Service;

import com.ermax.aircond.common.domain.UserGroup;

@Service("objectCompareService")
public class ObjectCompareService {

	public String compareSummary(Object previous, Object current) {
		StringBuilder sb = new StringBuilder();

		Class<?> c1 = previous.getClass();
		Class<?> c2 = current.getClass();

		if (!c1.getName().equals(c2.getName())) {
			sb.append("Different Class");
			return sb.toString();
		}

		Field[] fields = c1.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];

			String fieldName = field.getName();
			try {

				String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

				Method method1 = c1.getDeclaredMethod(methodName);
				Method method2 = c2.getDeclaredMethod(methodName);

				Object value1 = method1.invoke(previous);
				Object value2 = method2.invoke(current);

				if (!value1.equals(value2)) {
					sb.append(fieldName);
					sb.append(": ");
					sb.append(value1);
					sb.append(">>>");
					sb.append(value2);
					sb.append("	");
				}
			} catch (Exception e) {
			}

		}

		return sb.toString();
	}

	public static void main(String[] args) throws Exception {
		UserGroup ug1 = new UserGroup();
		ug1.setGroupName("AAA");
		ug1.setDescription("SYSTEM");
		UserGroup ug2 = new UserGroup();
		ug2.setGroupName("AA22A");
		ug2.setDescription("ADMIN");

		ObjectCompareService service = new ObjectCompareService();
		String result = service.compareSummary(ug1, ug2);
		System.out.println(result);

	}
}
